<?php
/**
 * Created by PhpStorm.
 * User: 汪利东
 * Date: 2016/3/24
 * Time: 16:49
 */

namespace Admin\Controller;


use Admin\Model\AdminGroupModel;

class AdminGroupController extends BaseController
{
    public function index()
    {
        $m = new AdminGroupModel();
        $data = $m->relation(true)->select();

        $this->data = $data;

        $this->display();
    }

    public function add()
    {
        $data = M('AdminRule')->select();
        $this->data = $data;

        $this->display('edit');
    }

    public function edit()
    {
        $id = I('get.id');

        $data = M('AdminRule')->select();

        $admin = M('AdminGroup')->where(['id' => $id])->find();
        $rulesArr = explode(',', $admin['rules']);
        foreach ($data as $k => $v) {
            if (in_array($v['id'], $rulesArr)) {
                $data[$k]['selected'] = true;
            }
        }

        $this->admin = $admin;
        $this->data = $data;

        $this->display();
    }

    public function doEdit()
    {
        $id = I('get.id');
        $data = M('AdminGroup')->create();
        $rules = I('post.rules');
        $data['rules'] = implode(',', $rules);
//        dump($_POST);
//        dump($id);dump($data);die;

        if (empty($id)) {
            //新增
            $r = M('AdminGroup')->add($data);
            if (!empty($r)) {
                $this->success('新增成功', U('index'));
            } else {
                $this->success('新增失败');
            }
        } else {
            //编辑
            $r = M('AdminGroup')->where(['id' => $id])->save($data);
            if (!empty($r)) {
                $this->success('修改成功');
            } else {
                $this->success('修改失败');
            }
        }
    }

    public function del()
    {
        $id = I('get.id');
        $r = M('AdminGroupHasUser')->where(['group_id' => $id])->count();
        if (!empty($r)) {
            $this->error('此角色下有用户，请先删除用户');
            exit;
        }

        $r = M('AdminGroup')->where(['id' => $id])->delete();
        if ($r) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败，请联系管理员');
        }
    }
}